package com.zp.self.module.工具.json转换.csv_json;

import org.springframework.data.annotation.Transient;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @author ：by peng.zeng
 * @date ：Created 2021/12/6 18:39
 * @description ：csv转为json对象
 */
public class Csv2Json {

    public static void main(String[] args) throws Exception {

        String in ="C:\\Users\\peng.zeng\\Desktop\\分析_工况-差值除去无用.csv";
        String out ="C:\\Users\\peng.zeng\\Desktop\\insert_03_10.json";
        extracted(in, out);

//        String in ="C:\\Users\\peng.zeng\\Desktop\\分析_工况 - 计算差值 - 单位错误.csv";
//        String out ="C:\\Users\\peng.zeng\\Desktop\\insert4.json";
//        extracted(in, out);

//         in ="C:\\Users\\peng.zeng\\Desktop\\report_2021.csv";
//         out ="C:\\Users\\peng.zeng\\Desktop\\report_2021.json";
//        extracted(in, out);

//        in ="C:\\Users\\peng.zeng\\Desktop\\support2020.csv";
//         out ="C:\\Users\\peng.zeng\\Desktop\\support2020.json";
//        extracted(in, out);
//
//        in ="C:\\Users\\peng.zeng\\Desktop\\support2021.csv";
//         out ="C:\\Users\\peng.zeng\\Desktop\\support2021.json";
//        extracted(in, out);


    }

    private static void extracted(String in, String out) throws Exception {
        InputStream filePath = new FileInputStream(in);
        OutputStream outPutPath = new FileOutputStream(out);
        Csv2Json csvToJSon = new Csv2Json();
        csvToJSon.ConvertToJson(filePath, outPutPath);
        System.out.println("处理完成。");
    }

    private List<String> stringToList(String s, String sep) {
        if (s == null)
            return null;
        String[] parts = s.split(sep);
        return Arrays.asList(parts);
    }

    @Transactional
    public String stringToJson(List<String> header, List<String> lineData) throws Exception {
        if (header == null || lineData == null) {
            throw new Exception("输入不能为null。");
        } else if (header.size() != lineData.size()) {
            throw new Exception("表头个数和数据列个数不等。");
        }
        StringBuilder sBuilder = new StringBuilder();
        sBuilder.append("{ ");
        for (int i = 0; i < header.size(); i++) {
            String mString = String.format("\"%s\":\"%s\"", header.get(i), lineData.get(i));
            sBuilder.append(mString);

            if (i != header.size() - 1) {
                sBuilder.append(", ");
            }
        }
        sBuilder.append(" }");

        return sBuilder.toString();
    }

    public void ConvertToJson(InputStream filePath, OutputStream outPutPath) throws Exception {
        InputStreamReader isr = new InputStreamReader(filePath, StandardCharsets.UTF_8);

        BufferedReader reader = new BufferedReader(isr);
        OutputStreamWriter osw = new OutputStreamWriter(outPutPath, StandardCharsets.UTF_8);
        BufferedWriter writer = new BufferedWriter(osw);


        try {
            String sep = ",";
            String headerStr = reader.readLine();

            if (headerStr.trim().isEmpty()) {
                System.out.println("表格头不能为空");
                return;
            }

            List<String> header = stringToList(headerStr, sep);
            String line;
            int lineCnt = 1;
            writer.write("[");
            while ((line = reader.readLine()) != null) {

                if (line.trim().isEmpty()) {
                    System.out.println("第" + lineCnt + "行为空，已跳过");
                    continue;
                }

                List<String> lineData = stringToList(line, sep);

                if (lineData.size() != header.size()) {
                    String mString = String.format("第%d行数据列和表头列个数不一致\r\n%s", lineCnt, line);
                    System.err.println(mString);
                    break;
                }

                String jsonStr = stringToJson(header, lineData);
                writer.write(jsonStr);
                writer.write("\r\n,");

                lineCnt++;
            }
        } finally {
            writer.write("]");
            if (reader != null) {
                reader.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }



}